package com.sxhuayuan.parking.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CrossDomainFilter implements Filter {

	Logger log = LoggerFactory.getLogger(getClass());

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		// HttpServletRequest request = (HttpServletRequest) servletRequest;
		// Enumeration<String> headerNames = request.getHeaderNames();
		// StringBuilder headers = new StringBuilder();
		// while (headerNames.hasMoreElements()) {
		// String key = headerNames.nextElement();
		// if (key.equals("cookie")) {
		// log.debug("cookie={}", request.getHeader(key));
		// } //
		// headers.append(key).append("=").append(request.getHeader(key)).append("\n");
		// }
		// log.debug("headers=\n{}", headers);
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.addHeader("Access-Control-Allow-Headers", "Content-Type, access-control-allow-credentials, access-control-allow-headers, access-control-allow-methods, access-control-allow-origin, hbtoken");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		chain.doFilter(servletRequest, response);
	}

	@Override
	public void destroy() {

	}
}
